package com.cssw.fyzb.tps.api.adapay;

import com.cssw.fyzb.tps.config.adapay.AdapayConfig;
import com.cssw.fyzb.tps.service.pay.AliPayService;
import com.huifu.adapay.model.Payment;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: yangyiqun
 * @Date: 2021/1/06 22:29
 */
@Function(description = "查询支付对象", parameters = {
        @Parameter(name = "tradeNo", type = Type.String, description = "外部单号", required = true)
})
@Component
public class QueryAdapay implements Action {

    private static final Logger logger = LoggerFactory.getLogger(QueryAdapay.class);

    @Autowired
    private AdapayConfig adapayConfig;

    @Override
    public Response execute(Request request) throws Exception {
        String tradeNo = request.getString("tradeNo");

        try {
            Map<String, Object> paymentParams = new HashMap<>(10);
            paymentParams.put("app_id", adapayConfig.getAppId());
            paymentParams.put("order_no", tradeNo);

            Map<String, Object> payment = Payment.queryList(paymentParams);

            if (null == payment){
                return Response.fail("订单接口异常");
            }
            if (null == payment.get("payments")){
                return Response.fail("订单不存在");
            }

            List<Map> payments = (List<Map>)payment.get("payments");
            if (null == payments || payments.size() != 1){
                return Response.fail("订单不存在");
            }

            Map paymentInfo = payments.get(0);

            //pending 交易处理中
            //succeeded 交易成功
            //failed 交易失败
//            if ("pending".equals(paymentInfo.get("status"))){
//                return Response.fail("订单未支付");
//            }
//            if (!"succeeded".equals(paymentInfo.get("status"))){
//                return Response.fail("订单支付失败");
//            }
            return Response.success().put("data", paymentInfo);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("支付查询失败");
        }
    }
}
